package com.youlai.boot.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.system.converter.SysLedgerConverter;
import com.youlai.boot.system.mapper.SysLedgerMapper;
import com.youlai.boot.system.model.dto.LedgerCountVO;
import com.youlai.boot.system.model.entity.SysLedger;
import com.youlai.boot.system.model.entity.User;
import com.youlai.boot.system.model.form.SysLedgerForm;
import com.youlai.boot.system.model.query.SysLedgerQuery;
import com.youlai.boot.system.model.vo.SysLedgerExcelVO;
import com.youlai.boot.system.model.vo.SysLedgerVO;
import com.youlai.boot.system.service.SysLedgerService;
import com.youlai.boot.system.service.UserService;
import com.youlai.boot.util.NumUtil;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 流水台账服务实现类
 *
 * @author youlaitech
 * @since 2025-05-12 15:55
 */
@Service
@RequiredArgsConstructor
public class SysLedgerServiceImpl extends ServiceImpl<SysLedgerMapper, SysLedger> implements SysLedgerService {

    private final SysLedgerConverter sysLedgerConverter;
    @Resource
    private UserService userService;

    @Value("${self.day:30}")
    private Long day;

    /**
     * 获取流水台账分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<SysLedgerVO>} 流水台账分页列表
     */
    @Override
    public IPage<SysLedgerVO> getSysLedgerPage(SysLedgerQuery queryParams) {
        Page<SysLedgerVO> pageVO = this.baseMapper.getSysLedgerPage(new Page<>(queryParams.getPageNum(), queryParams.getPageSize()), queryParams);
        return pageVO;
    }

    /**
     * 获取流水台账表单数据
     *
     * @param id 流水台账ID
     * @return
     */
    @Override
    public SysLedgerForm getSysLedgerFormData(Long id) {
        SysLedger entity = this.getById(id);
        return sysLedgerConverter.toForm(entity);
    }

    /**
     * 新增流水台账
     *
     * @param formData 流水台账表单对象
     * @return
     */
    @Override
    public boolean saveSysLedger(SysLedgerForm formData) {
        return this.save(buildLedger(formData));
    }

    /**
     * 更新流水台账
     *
     * @param id       流水台账ID
     * @param formData 流水台账表单对象
     * @return
     */
    @Override
    public boolean updateSysLedger(Long id, SysLedgerForm formData) {
        return this.updateById(buildLedger(formData));
    }

    /**
     * @param form
     */
    public SysLedger buildLedger(SysLedgerForm form) {
        //车牌号重复提示
        SysLedger sysLedger = baseMapper.selectByChepaihao(form.getId(), form.getChepaihao(), day);
        if (sysLedger != null) {
            String formattedTime = sysLedger.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            throw new BusinessException("车牌号:"+ form.getChepaihao()+"重复," +"最近填写时间:"+formattedTime);
        }

        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            throw new BusinessException("用户不存在");
        }
        User user = userService.getById(userId);
        String username = "";

        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        username = user.getNickname();
        SysLedger entity = sysLedgerConverter.toEntity(form);
        if (entity.getId() != null) {
            entity.setUpdateBy(userId);
            entity.setUpdateTime(LocalDateTime.now());
        } else {
            entity.setUserName(username);
            entity.setUserId(userId);
            entity.setCreateBy(userId);
            entity.setUpdateBy(userId);
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
        }
//
//        boolean kousui = form.getType() == 1;
//        //被保险人
//        String beibaoxianren = form.getBeibaoxianren();
//        //保险
//        BigDecimal qiangxian = form.getQiangxian();
//        BigDecimal shangyexian = form.getShangyexian();
//        BigDecimal jiachengxian = form.getJiachengxian();
//        BigDecimal chechuanxian = form.getChechuanxian();
//        //政策
//        BigDecimal qiangxianzhengce = form.getQiangxianzhengce();
//        BigDecimal shangyezhengce = form.getShangyezhengce();
//        BigDecimal jiachengxianzhengce = form.getJiachengxianzhengce();
//        //返点
//        BigDecimal qiangxianfandian = form.getQiangxianfandian();
//        BigDecimal shangyefandian = form.getShangyefandian();
//        BigDecimal jiachengfandian = form.getJiachengfandian();
//
//        //手续费汇总
//        BigDecimal shouXuFei = NumUtil.shouXuFei(beibaoxianren, kousui, qiangxian, qiangxianzhengce, shangyexian, shangyezhengce, jiachengxian, jiachengxianzhengce);
//        //返给业务员
//        BigDecimal yeWuYuan = NumUtil.yeWuYuan(kousui, qiangxian, shangyexian, jiachengxian, qiangxianfandian, shangyefandian, jiachengfandian);
//        //利润
//        BigDecimal liRun = NumUtil.liRun(shouXuFei, yeWuYuan);
//        //应收
//        BigDecimal yingShou = NumUtil.yingShou(beibaoxianren, kousui, qiangxian, shangyexian, chechuanxian, jiachengxian, yeWuYuan);
//
//        entity.setShouxufei(shouXuFei);
//        entity.setYingshou(yingShou);
//        entity.setLirun(liRun);
//        entity.setFangeiyewuyuan(yeWuYuan);
        return entity;
    }

    /**
     * 删除流水台账
     *
     * @param ids 流水台账ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteSysLedgers(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的流水台账数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).toList();
        return this.removeByIds(idList);
    }

    /**
     * @param queryParams
     * @return
     */
    @Override
    public List<SysLedgerExcelVO> exportList(SysLedgerQuery queryParams) {
        return this.baseMapper.exportList(queryParams);
    }

    /**
     * 获取流水台账统计数据
     *
     * @param queryParams
     * @return
     */
    @Override
    public LedgerCountVO getSysLedgerCount(SysLedgerQuery queryParams) {
        return this.baseMapper.getSysLedgerCount(queryParams);
    }
}
